/**
 @ Name layui.list
 @ Author jbf
 */
;layui.define(['layer','form','jquery','laydate'],function(exports){
    "use strict";

    var $ = layui.jquery
        ,layer = layui.layer
        ,form  = layui.form
        ,laydate=layui.laydate

        //字符常量
        ,MOD_NAME = 'list', ELEM = '.layui-list'
        ,TPL_HEAD=''
        ,TPL_FOOT=''
        ,TPL_MAIN = function(options){
            var colCal = 0;
            var laydates = [];
            var fields = options.fields || [];
            var over = options.over || [];
            var content = '<form action="'+(options.action||'')+'" class="layui-form'+(options.pane?' layui-form-pane':'')+'" id="JbfList_'+options.id+'" lay-filter="JbfList_'+options.id+'" style="padding: 20px 30px 0 0;">';

            for(var key in fields){
                //if(over[key] != undefined){  bug 修改
                fields[key].value = over[key];
               // }
            }

            layui.each(fields,function(i1,item1){
                var pane = '';
                item1.type = item1.type || 'text';
                if("hidden" == item1.type){
                    content += '<input type="hidden" name="'+i1+'" value="'+(item1.value||'')+'" />';
                    return;
                }
                if(/^checkbox|switch|radio|textarea$/.test(item1.type)){
                    pane = options.pane || '';
                }

                if(item1.col){
                    if(colCal == 0){
                        var space = item1.colSpace || 10;
                        content += '<div class="layui-row layui-col-space'+space+' layui-form-item" '+pane+'>';
                    }
                    content += '<div class="layui-col-md'+item1.col+'">';
                    colCal += item1.col;
                    if(colCal >= 12){
                        colCal = 0;
                    }
                }else{
                    if(colCal > 0){
                        colCal = 0;
                        content += '</div>';
                    }else{
                        content += '<div class="layui-form-item" '+pane+' >';
                    }
                }
                if(item1.label){
                    content += '<label class="layui-form-label">'+item1.label+'</label>';
                }
                content += '<div class="layui-input-'+(item1.display||'block')+' jbf-input-'+i1+'">';

                content += createField($.extend(true,{},options,{item:item1,index:i1}));
                if(item1.col){
                    content += '</div>';
                }
                if(colCal == 0){
                    content += '</div>';
                }

                content += '</div>';
            });

            content += '<div class="layui-form-item">';
            var btns = options.btns || [];
            content += '<div class="layui-input-block">';
            $(btns).each(function(){
                if(this == "submit"){
                    content += '<button class="layui-btn" lay-submit lay-filter="'+options.id+'SubmitBtn">立即提交</button>';
                }else if(this == "reset"){
                    content += '<button class="layui-btn layui-btn-primary" type="reset" lay-filter="submitBtn">重置</button>';
                }else if(this == "search"){
                    content += '<button class="layui-btn" lay-submit lay-filter="'+options.id+'SubmitBtn"><i class="layui-icon layui-icon-search"></i></button>';
                }
            });
            content += '</div>';
            content += '</div>';

            content += '</form>';

            return {
                content:content,
                laydates:laydates
            };
        }
        ,createField = function (options) {
            var placeholder,
                item1 = options.item,
                i1 = options.index|| 0;
            if(item1.label){
                placeholder = item1.placeholder || ("请输入"+item1.label);
            }
            var rd = '';

            if((item1.readonly == null && options.readonly)||(item1.readonly != null && item1.readonly != "false")){
                rd += ' readonly="readonly"';
            }
            if((item1.disabled == null && options.disabled)||(item1.disabled != null && item1.disabled != "false") ){
                rd += ' disabled="disabled"';
            }
            var content = "";
            if("text" == item1.type || "password" == item1.type){
                content += '<input lay-filter="'+i1+'Filter" autocomplete="off" class="layui-input" lay-verType="tips" lay-verify="'+(item1.verify||'required')+'"' +
                    ' type="'+item1.type+'" name="'+i1+'" value="'+(item1.value||'')+'"';
                content += 'placeholder="'+placeholder+'"';
                content += rd;
                if(item1.url) {
                    content += 'url = "'+item1.url+'"';
                }
                if(item1.exclud){
                    content += 'exclud = "'+item1.exclud+'"';
                }
                content += "/>";
            }else if("select" == item1.type){
                content += '<select lay-verType="tips" lay-filter="'+i1+'Filter" name="'+i1+'" lay-verify="'+(item1.verify||'required')+'"'+rd+'>';
                var source = item1.source;
                var displayName = item1.displayName || 'name';
                var valueName = item1.valueName || 'value';
                content += '<option value="">请选择</option>';
                if(typeof source == "string" ){
                    var gangedData = {};
                    if(item1.ganged){
                        try{
                            gangedData[item1.ganged] = options.fields[item1.ganged].value;
                        }catch(err){
                            //console.error("属性"+item1.ganged+"不存在"+err);
                            gangedData[item1.ganged] = gangedData[item1.ganged] || $("[name="+item1.ganged+"]").val();
                        }
                    }
                    $.ajax({
                        url : source,
                        dataType: "JSON",
                        data : gangedData,
                        async:false,
                        success:function(res){
                            source = res;
                        },
                        error:function(e){
                            source = [];
                            content += '<option value="">资源加载失败:'+e.statusText+'</option>';
                        }
                    });
                }
                $(source).each(function() {
                    content += '<option ';
                    if (this[valueName] == item1.value) {
                        content += "selected ";
                    }
                    content += 'value="' + this[valueName] + '">' + this[displayName] + '</option>';
                });
                content += '</select>';
            }else if("textarea" == item1.type){
                content +='<textarea name="'+i1+'" placeholder="'+placeholder+'"' + rd ;
                if(item1.verify){
                    content += 'lay-verify="' + item1.verify;
                }
                content += '" class="layui-textarea">'+(item1.value||'')+'</textarea>';
            }else if("radio" == item1.type){
                var source = item1.source;
                var displayName = item1.displayName || 'name';
                var valueName = item1.valueName || 'value';
                if(typeof source == "string"){
                    $.ajax({
                        url : source,
                        dataType: "JSON",
                        async:false,
                        success:function(res){
                            source = res;
                        },
                        error:function(e){
                            source = [];
                            console.log(e.statusText);
                        }
                    });
                }
                $(source).each(function(){
                    content += '<input lay-filter="'+i1+'Filter" type="radio" title="'+this[displayName]+'" value="'+this[valueName]+'" name="'+i1+'"' + rd;
                    if(item1.value == this.value){
                        content += " checked ";
                    }else if(this.checked){
                        content += " checked ";
                    }
                    content += "/>";
                });
            }else if("switch" == item1.type){
                content += '<input lay-filter="'+i1+'Filter" type="checkbox" name="'+i1+'" lay-skin="switch" lay-text="'+item1.text+'"';
                if(eval(item1.value)){
                    content += " checked ";
                }
                content += "/>"
            }else if("calendar" == item1.type){
                content += '<input autocomplete="off" class="layui-input" id="'+options.id+'_'+i1+'Calendar" name="'+i1+'" lay-verType="tips"';
                content += ' placeholder="'+placeholder+'"' +
                    ' lay-verify="'+(item1.verify||'required')+'" value="'+(item1.value||'')+'" />';
                laydates.push($.extend({elem:'#'+options.id+'_'+i1+'Calendar'},item1.config||{}));
            }
            return content ;
        }
        //实例方法
        ,list = {
            index : 0
            ,open : function(options){
                var openList = new Class(options);
                var ops = openList.config;
                var tpl = TPL_MAIN(ops);//{content:"",laydate:[],等其组件}
                layer.open($.extend(ops,{
                    content : tpl.content.toString(),
                    success : function(){
                        this.config = ops;
                        reRender.call(openList,tpl);
                    },
                    btn:[]
                }));
            }
        }
        //操作当前实例
        ,thisList = function(){
            var that = this
                ,options = that.config;    //获取默认配置
            options.id = options.id || options.index;
            return {
                reload: function(options){
                    that.reload.call(that, options);
                }
                ,config: options
            }
        }
        ,reRender = function(tplMain){
            var that = this,
                options = that.config,
                refElem = tplMain;
            //渲染表单
            var thisForm = form.render();
            //渲染日历控件
            var calendars = refElem.laydates;
            for(var i = 0;i < calendars.length;i++){
                var tempDate = calendars[i];
                laydate.render(tempDate);
            }
            //表单提交事件
            form.on('submit('+options.id+'SubmitBtn)',function(res){
                return options.submit(res);
            });


        }

        //构造器
        ,Class = function(options){
            var that = this;
            //给当前对象声明一个索引变量
            that.index = ++list.index;
            //合并配置项（{} 被 默认配置 覆盖， 被 用户配置 覆盖）
            that.config = $.extend({}, that.config, list.config, options);
        };
    //默认配置
    Class.prototype.config = {
        btns:['submit','reset'],
        area:"580px",
        btn : []
    };

    //渲染视图
    Class.prototype.render = function(){
        var that = this
            ,options = that.config;
        options.elem = $(options.elem);

        var refElem = TPL_MAIN(options);

        options.elem.html($(refElem.content));

        reRender.call(this,refElem);
    };

    //入口，渲染元素，返回当前模块的实例
    list.render = function(options){
        //实例化组件
        var ins = new Class(options);
        ins.render();
        return thisList.call(ins);
    };
    list.addField = function (options) {
        var field = options.field;
        var content =  createField({item:field, index: field.name});
        $(options.select).html(content);
        form.render(field.type);
        return content;
    }
    //拓展表单验证
    form.verify({
        exists : function(value,item){
            var msg;
            $.ajax({
                url : $(item).attr("url"),
                async:false,
                data:{target:value,exclud:$(item).attr("exclud")},
                success:function(data){
                    if(data.code == 404){
                        msg = data.msg;
                    }
                }
            });
            if(msg) return msg;
        }
    });
    //输出test接口
    exports('list', list);
});    